package com.fintech.third.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuartzService {
	private static final String JOB_GROUP = "event_job_group";
	private static final String TRIGGER_GROUP = "event_trigger_group";
	@Autowired
	private Scheduler scheduler;

	/**
	 * 创建定时任务
	 * 
	 * @param jobDetailName
	 * @param cronExpression
	 * @param jobClass
	 * @throws SchedulerException
	 */
	public void createScheduleJob(String jobDetailName, String cronExpression, Class<? extends Job> jobClass)
			throws SchedulerException {
		JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity("task_" + jobDetailName, JOB_GROUP)
				.storeDurably().requestRecovery().build();
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity("task_" + jobDetailName, TRIGGER_GROUP)
				.withSchedule(scheduleBuilder).build();
		scheduler.scheduleJob(jobDetail, trigger);
	}
}
